package com.putong35.common.account.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.putong35.common.BuildConfig;
import com.putong35.common.account.AccountManager;
import com.putong35.common.account.data.http.AccountApiHelper;
import com.putong35.common.app.data.HttpCommonApiHelper;
import com.putong35.common.baseactfrag.CompState;
import com.putong35.common.baseactfrag.activity.BaseActivity;
import com.putong35.common.databinding.ActivityRegisterBinding;
import com.putong35.common.utils.ActivityUtils;
import com.putong35.common.utils.EasyToast;
import com.putong35.common.utils.RegularUtils;
import com.putong35.common.utils.ui.EditTextHelper;

public class RegisterActivity extends BaseActivity {
    public static final String TAG = RegisterActivity.class.getSimpleName();

    public static void start(Context context) {
        Intent starter = new Intent(context, RegisterActivity.class);
        context.startActivity(starter);
    }

    /**
     * 通话倒计时90s
     */
    private CountDownTimer mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            activityRegisterBinding.btnSendCaptcha.setEnabled(false);
            activityRegisterBinding.btnSendCaptcha.setText(String.valueOf((millisUntilFinished / 1000) + "s"));
        }

        @Override
        public void onFinish() {
            activityRegisterBinding.btnSendCaptcha.setEnabled(true);
            activityRegisterBinding.btnSendCaptcha.setText("发送验证码");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        hideToolbar();
//        statusTransucentAndLayoutFullscreen();
        EditTextHelper.setToPhoneType(activityRegisterBinding.etAccountID);
        getCustomToolbar().setBackgroundColor(getColor(android.R.color.white));
        enableBackButton();
        getCustomToolbar().hideBottomLine();
        setTitle("");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AccountManager.getInstance().getAccount() != null) {
            setResult(RESULT_OK);
            EasyToast.showToast(this, "用户已登录");
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    ActivityRegisterBinding activityRegisterBinding;
    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activityRegisterBinding = ActivityRegisterBinding.inflate(inflater);
        activityRegisterBinding.setViewModel(this);
        EditTextHelper.setToPhoneType(activityRegisterBinding.etAccountID, 11);

        setEditTextWatcher(activityRegisterBinding.etAccountID);
        setEditTextWatcher(activityRegisterBinding.etCaptcha);
        setEditTextWatcher(activityRegisterBinding.etPwd1);
        setEditTextWatcher(activityRegisterBinding.etPwd2);

        if (BuildConfig.DEBUG) {
            activityRegisterBinding.etAccountID.setText("15959235111");
            activityRegisterBinding.etPwd1.setText("11111111");
            activityRegisterBinding.etPwd2.setText("11111111");
            activityRegisterBinding.etCaptcha.setText("0000");
        }

        return activityRegisterBinding .getRoot();
    }

    private void setEditTextWatcher(EditText et) {
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override

            public void afterTextChanged(Editable editable) {
                String accountId = activityRegisterBinding.etAccountID.getText().toString().trim();
                String pwd1 = activityRegisterBinding.etPwd1.getText().toString().trim();
                String pwd2 = activityRegisterBinding.etPwd2.getText().toString().trim();
                String captcha = activityRegisterBinding.etCaptcha.getText().toString().trim();

                if (!TextUtils.isEmpty(accountId)
                        && !TextUtils.isEmpty(pwd1)
                        && !TextUtils.isEmpty(pwd2)
                        && !TextUtils.isEmpty(captcha)) {
                    activityRegisterBinding.btnRegister.setEnabled(true);
                } else {
                    activityRegisterBinding.btnRegister.setEnabled(false);
                }
            }
        });
    }

    public void reqRegister() {
        String inputMobile = activityRegisterBinding.etAccountID.getText().toString();
        String pwd = activityRegisterBinding.etPwd1.getText().toString().trim();
        String pwd2 = activityRegisterBinding.etPwd2.getText().toString().trim();
        String captcha = activityRegisterBinding.etCaptcha.getText().toString();

        if(TextUtils.isEmpty(inputMobile)) {
            EasyToast.showToast(this, "手机号码不能为空");
            return;
        }

        if(!RegularUtils.isMobileSimple(inputMobile)) {
            EasyToast.showToast(this, "请输入有效的手机号");
            return;
        }

        if(TextUtils.isEmpty(pwd)) {
            EasyToast.showToast(this, "密码不能为空");
            return;
        } else if (pwd.length() > 20 || pwd.length() < 8) {
            EasyToast.showToast(this, "请输入8-20位的密码");
            return;
        } else if (!TextUtils.equals(pwd, pwd2)) {
            EasyToast.showToast(this, "两次输入的密码不一致");
            return;
        }

        if(TextUtils.isEmpty(captcha)) {
            EasyToast.showToast(this, "验证码不能为空");
            return;
        } else if (captcha.length() < 4) {
            EasyToast.showToast(this, "请输入有效的6位验证码");
            return;
        }

        String inviteCode = activityRegisterBinding.etInviteCode.getText().toString().trim();

        setState(CompState.EMPTY_REFRESHING);
        AccountApiHelper.register(inputMobile, pwd, captcha, inviteCode, (code, msg, data, extObj) -> {
            Log.d(TAG, "onSuccess: " + data);
            AccountManager.getInstance().setAccount(data);
            setState(CompState.DATA);
            EasyToast.showToast(RegisterActivity.this, "注册成功");
            setResult(RESULT_OK);
            finish();

        }, (errCode, msg) -> {
            Log.d(TAG, "onFailure: " + msg);
            EasyToast.showToast(RegisterActivity.this, msg);
            setState(CompState.DATA);
        });


        /*
          UrlParams urlParams = new UrlParams();
        urlParams.put("mobile", inputMobile);
        urlParams.put("password", pwd);
        urlParams.put("code", captcha);


        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                TokenInfo tokenInfo = new TokenInfo();
                tokenInfo.setAccessToken("111111111111");
                tokenInfo.setExpiresAt("" + (System.currentTimeMillis() + 2000000000));
                tokenInfo.setMacKey("22222222");
                tokenInfo.setServerTime("" + System.currentTimeMillis());
                Token.getInstance().updateTokenInfo(tokenInfo);
                Thread.sleep(600);
                e.onComplete();
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("pww", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(Object value) {
                        Log.e("pww", "onNext: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("pww", "onError: ");
                        setState(CompState.DATA);
                    }

                    @Override
                    public void onComplete() {
                        reqUserInfo("test token");
                    }
                });*/

    }


//    public void reqUserInfo(String token) {
//        UrlParams urlParams = new UrlParams();
//        urlParams.put("token", token);
//
//        setState(CompState.EMPTY_REFRESHING);
//        Observable.create(new ObservableOnSubscribe<Object>() {
//            @Override
//            public void subscribe(ObservableEmitter<Object> e) throws Exception {
//              /*  String responseStr = AssetsUtil.getStringFromAssets(context, "request_login_data.txt");
//                Response parser = new Response(Account.class);
//                parser.setDataString(responseStr);
//                Account account = (Account) parser.getDataListBean();*/
//                Account account = new Account();
//                account.setName("小黄猫");
//                account.setPhone("15959234090");
//                account.setId("111111");
//                String imgUrl = "http://img01.taopic.com/160203/235110-1602030ZP835.jpg";
//                account.setPortraitUrl(imgUrl);
//                account.setBirthday(new Date().getTime() - 1000*60*60*24*30);
//                AccountManager.getInstance().setAccount(account);
//                Thread.sleep(2000);
//                e.onComplete();
//            }
//        }).observeOn(AndroidSchedulers.mainThread())
//                .subscribeOn(Schedulers.newThread())
//                .subscribe(new Observer<Object>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        Log.e("pww", "onSubscribe: ");
//                    }
//
//                    @Override
//                    public void onNext(Object value) {
//                        Log.e("pww", "onNext: ");
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        Log.e("pww", "onError: ");
//                        setState(CompState.DATA);
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        setState(CompState.DATA);
//                        setResult(RESULT_OK);
//                        finish();
//                    }
//                });
//    }



    public void reqCaptcha() {
        String inputMobile = activityRegisterBinding.etAccountID.getText().toString();
        if(TextUtils.isEmpty(inputMobile)) {
            EasyToast.showToast(this, "手机号码不能为空");
            return;
        }

        if(!RegularUtils.isMobileSimple(inputMobile)) {
            EasyToast.showToast(this, "请输入有效的手机号");
            return;
        }


        setState(CompState.EMPTY_REFRESHING);
      /*  Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                Thread.sleep(1000);
                e.onComplete();
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("pww", "reqUserInfo onSubscribe: ");
                    }

                    @Override
                    public void onNext(Object value) {
                        Log.e("pww", "reqUserInfo onNext: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("pww", "reqUserInfo onError: ");
                        e.printStackTrace();
                        setState(CompState.DATA);
                    }

                    @Override
                    public void onComplete() {
                        setState(CompState.DATA);
                        EasyToast.showToast(RegisterActivity.this, "验证码已发送！");
                    }
                });*/

        HttpCommonApiHelper.getSmsCode(AccountApiHelper.SMS_TYPE_REGISTER, inputMobile, (code, msg, data, extObj) -> {
            Log.d(TAG, "onSuccess: " + data);
            EasyToast.showToast(RegisterActivity.this, "验证码已发送！");
            setState(CompState.DATA);

        }, (errCode, msg) -> {
            Log.d(TAG, "onFailure: " + msg);
            setState(CompState.DATA);
        });

        mCountDownTimer.start();
    }


    public void clkGoLogin() {
        ActivityUtils.startActivity(this, LoginActivity.class);
        finish();
    }
}
